package com.inkyi.assistant.app.todolist.right;

import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLightLaf;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import com.inkyi.assistant.app.todolist.TodoContext;
import com.inkyi.assistant.app.todolist.event.TodoEvent;
import com.inkyi.assistant.app.todolist.table.TodoItem;
import com.inkyi.assistant.app.todolist.table.TodoListSelectionListener;
import com.inkyi.assistant.app.todolist.table.TodoTableModel;
import com.inkyi.assistant.app.todolist.table.TodoTableModelListener;
import com.inkyi.framework.daqian.share.datepicker.DatePickerField;
import net.miginfocom.swing.MigLayout;

import javax.swing.*;
import javax.swing.table.TableColumnModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class TodoRightMainContent extends JPanel {

    private JLabel currDayLabel;
    private JTextField titleField;
    private DatePickerField datePickerField;
    private JTable todoTable;
    private JTable completedTable;
    private TodoTableModel todoTableModel;
    private TodoTableModel completedTableModel;


    public TodoRightMainContent() {
        initComponents();
    }

    private void initComponents() {
        setupUI();
        initConfig();
    }

    private void initConfig() {
        // 回车添加待办
        titleField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String text = titleField.getText();
                if (text != null && !text.isEmpty()) {
                    String dateText = datePickerField.getText();
                    TodoEvent todoEvent = TodoEvent.of(e.getSource(), TodoEvent.TYPE_RECORD_NEW);
                    todoEvent.getParams().put("title", text);
                    todoEvent.getParams().put("todoTime", LocalDate.parse(dateText, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    TodoContext.getEventWrap().fireActionEvent(todoEvent);
                }
            }
        });
        // 待办事件完成
        TodoTableModelListener tableModelListener = new TodoTableModelListener();
        todoTableModel.addTableModelListener(tableModelListener);
        completedTableModel.addTableModelListener(tableModelListener);
        // 选中待办事件，展示详情
        todoTable.getSelectionModel().addListSelectionListener(new TodoListSelectionListener(todoTable));
        completedTable.getSelectionModel().addListSelectionListener(new TodoListSelectionListener(completedTable));

        JPopupMenu tablePopupMenu = new JPopupMenu();
        JMenuItem delTaskMi = new JMenuItem("删除");
        JMenuItem finishTaskMi = new JMenuItem("完成");
        JMenuItem moveTaskMi = new JMenuItem("移动到");
        tablePopupMenu.add(delTaskMi);
        tablePopupMenu.add(finishTaskMi);
        tablePopupMenu.add(moveTaskMi);
        todoTable.setComponentPopupMenu(tablePopupMenu);
        completedTable.setComponentPopupMenu(tablePopupMenu);
    }

    private void setupUI() {

        this.setLayout(new MigLayout("", "", ""));

        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日 EEEE", Locale.CHINA);
        currDayLabel = new JLabel("今日（" + today.format(formatter) + "）");
        this.add(currDayLabel, "left, pushx, growx, wrap");

        titleField = new JTextField();
        titleField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "添加待办事件，按回车保存");
        titleField.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, new FlatSVGIcon("icons/todolist/plussign.svg", 18, 18));
        datePickerField = new DatePickerField();

        this.add(titleField, "split2, pushx, growx");
        this.add(datePickerField, "wrap");

        todoTableModel = new TodoTableModel();
        todoTable = new JTable();
        todoTable.setShowHorizontalLines(true);
        todoTable.setAutoCreateRowSorter(true);
        todoTable.setRowHeight(30);
        todoTable.setTableHeader(null);
        todoTable.setModel(todoTableModel);
        todoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumnModel todoCm = todoTable.getColumnModel();
        todoCm.getColumn(0).setMaxWidth(0);
        todoCm.getColumn(0).setMinWidth(0);
        todoCm.getColumn(0).setPreferredWidth(0);
        todoCm.getColumn(1).setMaxWidth(60);
        this.add(new JLabel("待办"), "left, wrap");
        this.add(new JScrollPane(todoTable), "span, push, grow, wrap");

        completedTableModel = new TodoTableModel();
        completedTable = new JTable();
        completedTable.setShowHorizontalLines(true);
        completedTable.setAutoCreateRowSorter(true);
        completedTable.setRowHeight(30);
        completedTable.setTableHeader(null);
        completedTable.setModel(completedTableModel);
        completedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumnModel completedCm = completedTable.getColumnModel();
        completedCm.getColumn(0).setMaxWidth(0);
        completedCm.getColumn(0).setMinWidth(0);
        completedCm.getColumn(0).setPreferredWidth(0);
        completedCm.getColumn(1).setMaxWidth(60);
        this.add(new JLabel("完成"), "left, wrap");
        this.add(new JScrollPane(completedTable), "span, push, grow, wrap");
    }

    public JTable getTodoTable() {
        return todoTable;
    }

    public JTable getCompletedTable() {
        return completedTable;
    }

    public TodoTableModel getTodoTableModel() {
        return todoTableModel;
    }

    public TodoTableModel getCompletedTableModel() {
        return completedTableModel;
    }

    public JTextField getTitleField() {
        return titleField;
    }

    public void clearTodoSelection() {
        todoTable.clearSelection();
        completedTable.clearSelection();
    }

    public void clearTodoItems() {
        todoTableModel.setRowCount(0);
        completedTableModel.setRowCount(0);
    }

    /**
     * 更新完成
     *
     * @param item 项
     */
    public void updateFinish(TodoItem item) {
        if (item == null) {
            return;
        }
        Serializable pk = item.getPk();
        Boolean isFinish = item.getFinish();
        TodoItem tableItem = todoTableModel.getValueByPk(pk);
        if (tableItem == null) {
            tableItem = completedTableModel.getValueByPk(pk);
        }
        if (tableItem == null) {
            return;
        }
        tableItem.setFinish(isFinish);
        todoTableModel.removeRowByPk(pk);
        completedTableModel.removeRowByPk(pk);
        if (isFinish) {
            completedTableModel.addRow(tableItem);
        } else {
            todoTableModel.addRow(tableItem);
        }
    }

    public void addTodoItems(List<TodoItem> itemList) {
        if (itemList == null || itemList.isEmpty()) {
            return;
        }
        for (TodoItem item : itemList) {
            if (item.getFinish()) {
                completedTableModel.insertRow(0, item);
            } else {
                todoTableModel.insertRow(0, item);
            }
        }
    }

    public List<TodoItem> findTodoSelection() {
        List<TodoItem> list = new ArrayList<>();
        int[] completedSelectRows = completedTable.getSelectedRows();
        for (int row : completedSelectRows) {
            list.add(completedTableModel.getValueByRow(row));
        }
        int[] todoSelectRows = todoTable.getSelectedRows();
        for (int row : todoSelectRows) {
            list.add(todoTableModel.getValueByRow(row));
        }
        return list;
    }

    public void delTodoItems(List<TodoItem> itemList) {
        if (itemList == null || itemList.isEmpty()) {
            return;
        }
        for (TodoItem item : itemList) {
            completedTableModel.removeRowByPk(item.getPk());
            todoTableModel.removeRowByPk(item.getPk());
        }
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception ex) {
            System.err.println("Failed to initialize LaF");
        }

        TodoRightMainContent contentPane = new TodoRightMainContent();
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }


}
